The course seems interesting but quite hard. Let’s see. I’m hoping to learn how to use GitHub and R Markdown and better my skills with R. I heard about the course through an email send by my doctoral school.
https://github.com/SarKin-bit/IODS-project
# This is a so-called "R chunk" where you can write R code.
date()
## [1] "Fri Dec 4 03:08:48 2020"
The text continues here…
learning2014<- read.delim("learning2014.txt")
dim(learning2014)
## [1] 166 7
str(learning2014)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : chr "F" "M" "F" "M" ...
## $ Age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ Attitude: int 37 31 25 35 37 38 35 29 38 21 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ Points : int 25 12 24 10 22 21 21 31 24 26 ...
There are 166 observations (rows) and 7 variables (columns). Columns are called gender, age, attitude, deep, stra, surf and points. All columns include data in numerical form, except column “gender”, which includes only characters.
Graphical overview of the data: Initialize plot with data and aesthetic mapping.
library(ggplot2)
p1 <- ggplot(learning2014, aes(x = Attitude, y = Points, col = gender))
Define the visualization type (points).
p2 <- p1 + geom_point()
Draw the plot.
p2
Add a regression line.
p3 <- p2 + geom_smooth(method = "lm")
p3
## `geom_smooth()` using formula 'y ~ x'
Summaries of the variables in the data.
summary(learning2014)
## gender Age Attitude deep
## Length:166 Min. :17.00 Min. :14.00 Min. :1.583
## Class :character 1st Qu.:21.00 1st Qu.:26.00 1st Qu.:3.333
## Mode :character Median :22.00 Median :32.00 Median :3.667
## Mean :25.51 Mean :31.43 Mean :3.680
## 3rd Qu.:27.00 3rd Qu.:37.00 3rd Qu.:4.083
## Max. :55.00 Max. :50.00 Max. :4.917
## stra surf Points
## Min. :1.250 Min. :1.583 Min. : 7.00
## 1st Qu.:2.625 1st Qu.:2.417 1st Qu.:19.00
## Median :3.188 Median :2.833 Median :23.00
## Mean :3.121 Mean :2.787 Mean :22.72
## 3rd Qu.:3.625 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :5.000 Max. :4.333 Max. :33.00
There seems to be a somewhat positive correlation here but distributions of the variables are scattered quite a bit and some are quite far from the regression line, meaning that the fit of the model is not perfect.
Setting three variables as explanatory variables and fitting a regression model where exam points is the (dependent) variable:
Create an plot matrix with ggpairs().
library(GGally)
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(ggplot2)
ggpairs(learning2014, lower = list(combo = wrap("facethist", bins = 20)))
Create a regression model with multiple explanatory variables.
my_model2 <- lm(Points ~ Attitude + stra + deep, data = learning2014)
Print out a summary of the model.
summary(my_model2)
##
## Call:
## lm(formula = Points ~ Attitude + stra + deep, data = learning2014)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.5239 -3.4276 0.5474 3.8220 11.5112
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.39145 3.40775 3.343 0.00103 **
## Attitude 0.35254 0.05683 6.203 4.44e-09 ***
## stra 0.96208 0.53668 1.793 0.07489 .
## deep -0.74920 0.75066 -0.998 0.31974
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.289 on 162 degrees of freedom
## Multiple R-squared: 0.2097, Adjusted R-squared: 0.195
## F-statistic: 14.33 on 3 and 162 DF, p-value: 2.521e-08
Relationship with the explanatory variable “Attitude” and response variable “Points” is statistically significant (p<0.05). Relationship with the explanatory variables “stra” and “deep” are not statistically significant with response variable “Points” (p>0.05).
Redo the model without the variables that had no statistical significance. I did a simple regression as two of the explanatory variables had no significant effect.
A scatter plot of points versus attitude.
qplot(Attitude, Points, data = learning2014) + geom_smooth(method = "lm")
## `geom_smooth()` using formula 'y ~ x'
Fit a linear model.
my_model3 <- lm(Points ~ Attitude, data = learning2014)
summary(my_model3)
##
## Call:
## lm(formula = Points ~ Attitude, data = learning2014)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.63715 1.83035 6.358 1.95e-09 ***
## Attitude 0.35255 0.05674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
Relationship between the target variable (Points) and the explanatory variable (Attitude) is statistically significant (p<0.05). Multiple R squared is 0.1906. It is quite low (compared to 1), which means that the data is not that close to the fitted regression line.This indicates that the model explains only some of the variability of the response data around its mean. The model does not seem to fit the data very well.
Draw diagnostic plots Residuals vs Fitted values, Normal QQ-plot and Residuals vs Leverage.
par(mfrow = c(2,2))
plot(my_model2, which = c(1,2,5))
Assumptions of the model are of that of linear regression:Linear relationship, multivariate normality, no or little multicollinearity, no auto-correlation and homoscedasticity.
In the Residuals vs Fitted values the red line is not perfectly flat, which indicates that there is discernible non-linear trend to the residuals. The residuals do not appear to be equally distributed across the entire range of the fitted values.
In the Normal QQ-plot the we can see thet the residuals are not normally distributed as the residual devide from the diagonal line.
In the Residuals vs Leverage there are no cases beyond the Cook’s distance lines which means that there is not any influential cases, i.e. there are no influential outliers.
date()
## [1] "Fri Dec 4 03:08:53 2020"
Here we go again…
alc<-read.table(file = "alc.txt", sep="\t", header=TRUE)
dim(alc)
## [1] 382 35
str(alc)
## 'data.frame': 382 obs. of 35 variables:
## $ school : chr "GP" "GP" "GP" "GP" ...
## $ sex : chr "F" "F" "F" "F" ...
## $ age : int 18 17 15 15 16 16 16 17 15 15 ...
## $ address : chr "U" "U" "U" "U" ...
## $ famsize : chr "GT3" "GT3" "LE3" "GT3" ...
## $ Pstatus : chr "A" "T" "T" "T" ...
## $ Medu : int 4 1 1 4 3 4 2 4 3 3 ...
## $ Fedu : int 4 1 1 2 3 3 2 4 2 4 ...
## $ Mjob : chr "at_home" "at_home" "at_home" "health" ...
## $ Fjob : chr "teacher" "other" "other" "services" ...
## $ reason : chr "course" "course" "other" "home" ...
## $ nursery : chr "yes" "no" "yes" "yes" ...
## $ internet : chr "no" "yes" "yes" "yes" ...
## $ guardian : chr "mother" "father" "mother" "mother" ...
## $ traveltime: int 2 1 1 1 1 1 1 2 1 1 ...
## $ studytime : int 2 2 2 3 2 2 2 2 2 2 ...
## $ failures : int 0 0 2 0 0 0 0 0 0 0 ...
## $ schoolsup : chr "yes" "no" "yes" "no" ...
## $ famsup : chr "no" "yes" "no" "yes" ...
## $ paid : chr "no" "no" "yes" "yes" ...
## $ activities: chr "no" "no" "no" "yes" ...
## $ higher : chr "yes" "yes" "yes" "yes" ...
## $ romantic : chr "no" "no" "no" "yes" ...
## $ famrel : int 4 5 4 3 4 5 4 4 4 5 ...
## $ freetime : int 3 3 3 2 3 4 4 1 2 5 ...
## $ goout : int 4 3 2 2 2 2 4 4 2 1 ...
## $ Dalc : int 1 1 2 1 1 1 1 1 1 1 ...
## $ Walc : int 1 1 3 1 2 2 1 1 1 1 ...
## $ health : int 3 3 3 5 5 5 3 1 1 5 ...
## $ absences : int 5 3 8 1 2 8 0 4 0 0 ...
## $ G1 : int 2 7 10 14 8 14 12 8 16 13 ...
## $ G2 : int 8 8 10 14 12 14 12 9 17 14 ...
## $ G3 : int 8 8 11 14 12 14 12 10 18 14 ...
## $ alc_use : num 1 1 2.5 1 1.5 1.5 1 1 1 1 ...
## $ high_use : logi FALSE FALSE TRUE FALSE FALSE FALSE ...
Access the tidyverse libraries tidyr, dplyr, ggplot2.
library(tidyr); library(dplyr); library(ggplot2)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
Glimpse at the alc data.
glimpse(alc)
## Rows: 382
## Columns: 35
## $ school <chr> "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP"…
## $ sex <chr> "F", "F", "F", "F", "F", "M", "M", "F", "M", "M", "F", "F"…
## $ age <int> 18, 17, 15, 15, 16, 16, 16, 17, 15, 15, 15, 15, 15, 15, 15…
## $ address <chr> "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U"…
## $ famsize <chr> "GT3", "GT3", "LE3", "GT3", "GT3", "LE3", "LE3", "GT3", "L…
## $ Pstatus <chr> "A", "T", "T", "T", "T", "T", "T", "A", "A", "T", "T", "T"…
## $ Medu <int> 4, 1, 1, 4, 3, 4, 2, 4, 3, 3, 4, 2, 4, 4, 2, 4, 4, 3, 3, 4…
## $ Fedu <int> 4, 1, 1, 2, 3, 3, 2, 4, 2, 4, 4, 1, 4, 3, 2, 4, 4, 3, 2, 3…
## $ Mjob <chr> "at_home", "at_home", "at_home", "health", "other", "servi…
## $ Fjob <chr> "teacher", "other", "other", "services", "other", "other",…
## $ reason <chr> "course", "course", "other", "home", "home", "reputation",…
## $ nursery <chr> "yes", "no", "yes", "yes", "yes", "yes", "yes", "yes", "ye…
## $ internet <chr> "no", "yes", "yes", "yes", "no", "yes", "yes", "no", "yes"…
## $ guardian <chr> "mother", "father", "mother", "mother", "father", "mother"…
## $ traveltime <int> 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1, 2, 1, 1, 1, 3, 1, 1…
## $ studytime <int> 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 1, 2, 3, 1, 3, 2, 1, 1…
## $ failures <int> 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0…
## $ schoolsup <chr> "yes", "no", "yes", "no", "no", "no", "no", "yes", "no", "…
## $ famsup <chr> "no", "yes", "no", "yes", "yes", "yes", "no", "yes", "yes"…
## $ paid <chr> "no", "no", "yes", "yes", "yes", "yes", "no", "no", "yes",…
## $ activities <chr> "no", "no", "no", "yes", "no", "yes", "no", "no", "no", "y…
## $ higher <chr> "yes", "yes", "yes", "yes", "yes", "yes", "yes", "yes", "y…
## $ romantic <chr> "no", "no", "no", "yes", "no", "no", "no", "no", "no", "no…
## $ famrel <int> 4, 5, 4, 3, 4, 5, 4, 4, 4, 5, 3, 5, 4, 5, 4, 4, 3, 5, 5, 3…
## $ freetime <int> 3, 3, 3, 2, 3, 4, 4, 1, 2, 5, 3, 2, 3, 4, 5, 4, 2, 3, 5, 1…
## $ goout <int> 4, 3, 2, 2, 2, 2, 4, 4, 2, 1, 3, 2, 3, 3, 2, 4, 3, 2, 5, 3…
## $ Dalc <int> 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1…
## $ Walc <int> 1, 1, 3, 1, 2, 2, 1, 1, 1, 1, 2, 1, 3, 2, 1, 2, 2, 1, 4, 3…
## $ health <int> 3, 3, 3, 5, 5, 5, 3, 1, 1, 5, 2, 4, 5, 3, 3, 2, 2, 4, 5, 5…
## $ absences <int> 5, 3, 8, 1, 2, 8, 0, 4, 0, 0, 1, 2, 1, 1, 0, 5, 8, 3, 9, 5…
## $ G1 <int> 2, 7, 10, 14, 8, 14, 12, 8, 16, 13, 12, 10, 13, 11, 14, 16…
## $ G2 <int> 8, 8, 10, 14, 12, 14, 12, 9, 17, 14, 11, 12, 14, 11, 15, 1…
## $ G3 <int> 8, 8, 11, 14, 12, 14, 12, 10, 18, 14, 12, 12, 13, 12, 16, …
## $ alc_use <dbl> 1.0, 1.0, 2.5, 1.0, 1.5, 1.5, 1.0, 1.0, 1.0, 1.0, 1.5, 1.0…
## $ high_use <lgl> FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FAL…
Use gather() to gather columns into key-value pairs and then glimpse() at the resulting data.
gather(alc) %>% glimpse
## Rows: 13,370
## Columns: 2
## $ key <chr> "school", "school", "school", "school", "school", "school", "sc…
## $ value <chr> "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP", "GP…
Draw a bar plot of each variable.
gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar()
There are 382 observations (rows) and 35 variables (columns). Variables in the data are for example school, sex, age, adress, family size, family educational support, free time after school and internet access at home. For more detailed explanation of the variables, please visit: https://archive.ics.uci.edu/ml/datasets/Student+Performance
Chosen interesting variables: student’s grade, school, home address type and student’s health.
Hypothesis 1: There is a relationship between alcohol use and student’s grade. Hypothesis 2: There is a relationship between alcohol use and student’s absences. Hypothesis 3: There is a relationship between alcohol use and student’s health. Hypothesis 4: There is a relationship between alcohol use and student’s quality of family relationships.
Hypothesis 1: There is a relationship between alcohol use and student’s grade.
attach(alc)
table(G3,high_use,sex)
## , , sex = F
##
## high_use
## G3 FALSE TRUE
## 0 0 0
## 2 0 0
## 3 0 0
## 4 3 0
## 5 3 0
## 6 11 2
## 7 3 1
## 8 14 3
## 9 2 1
## 10 25 6
## 11 10 6
## 12 33 10
## 13 8 3
## 14 15 3
## 15 10 1
## 16 13 4
## 17 2 2
## 18 4 0
##
## , , sex = M
##
## high_use
## G3 FALSE TRUE
## 0 1 1
## 2 0 1
## 3 1 0
## 4 3 1
## 5 1 2
## 6 4 5
## 7 1 1
## 8 5 5
## 9 1 3
## 10 13 20
## 11 6 4
## 12 21 17
## 13 11 4
## 14 16 4
## 15 5 0
## 16 17 4
## 17 3 0
## 18 3 0
library(ggplot2)
Initialise a plot of high_use and G3
g1 <- ggplot(alc, aes(x = high_use, y = G3, col = sex))
Define the plot as a boxplot and draw it.
g1 + geom_boxplot() + ylab("grade")
Initialise a plot of high use and sex.
g2<-ggplot(data = alc, aes(x = high_use, fill = sex))
Define the plot as a bar lot and draw it.
g2 + geom_bar()+facet_wrap("sex")
Male students who have high usage of alcohol (use a lot of alcohol) have lower grades than men who do not use a lot of alcohol. For female students, the high use of alcohol does not affect the grade.
Hypothesis 2: There is a relationship between alcohol use and student’s absences.
attach(alc)
## The following objects are masked from alc (pos = 3):
##
## absences, activities, address, age, alc_use, Dalc, failures,
## famrel, famsize, famsup, Fedu, Fjob, freetime, G1, G2, G3, goout,
## guardian, health, high_use, higher, internet, Medu, Mjob, nursery,
## paid, Pstatus, reason, romantic, school, schoolsup, sex, studytime,
## traveltime, Walc
table(G3,absences,sex)
## , , sex = F
##
## absences
## G3 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 26 27 29 44
## 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 4 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 5 0 0 2 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 6 5 3 0 1 1 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 7 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
## 8 1 2 4 1 0 2 2 1 0 0 1 0 0 1 0 0 0 0 0 0 2 0 0 0 0
## 9 0 0 2 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 10 5 4 4 1 4 1 1 1 1 1 2 0 0 0 2 1 0 0 0 2 0 0 0 0 0
## 11 2 2 1 2 1 3 0 0 2 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1
## 12 5 5 14 5 2 1 2 1 5 2 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
## 13 0 2 2 2 1 0 1 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 14 2 4 0 3 3 2 0 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0
## 15 3 0 4 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
## 16 5 1 3 0 1 2 3 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
## 17 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
## 18 2 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## absences
## G3 45
## 0 0
## 2 0
## 3 0
## 4 0
## 5 0
## 6 0
## 7 0
## 8 0
## 9 0
## 10 1
## 11 0
## 12 0
## 13 0
## 14 0
## 15 0
## 16 0
## 17 0
## 18 0
##
## , , sex = M
##
## absences
## G3 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 26 27 29 44
## 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 2 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 3 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
## 4 0 0 1 0 1 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 5 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 6 1 1 1 3 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0
## 7 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 8 1 1 0 0 4 0 0 0 1 0 1 0 2 0 0 0 0 0 0 0 0 0 0 0 0
## 9 0 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
## 10 4 4 5 2 3 4 2 1 2 2 0 0 1 0 2 0 1 0 0 0 0 0 0 0 0
## 11 1 2 0 1 1 2 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0
## 12 8 8 4 3 2 1 1 2 2 3 1 1 0 0 1 0 0 1 0 0 0 0 0 0 0
## 13 2 2 2 5 3 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
## 14 4 2 3 4 2 0 3 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
## 15 0 1 0 1 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 16 5 4 3 1 2 1 2 0 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 17 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 18 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## absences
## G3 45
## 0 0
## 2 0
## 3 0
## 4 0
## 5 0
## 6 0
## 7 0
## 8 0
## 9 0
## 10 0
## 11 0
## 12 0
## 13 0
## 14 0
## 15 0
## 16 0
## 17 0
## 18 0
library(ggplot2)
Initialise a plot of high_use and absences.
g3 <- ggplot(alc, aes(x = high_use, y = absences, col = sex))
Define the plot as a boxplot and draw it.
g3 + geom_boxplot() + ggtitle("Student absences by alcohol consumption")
For male students, high users of alcohol have more absences from school. For female students, the number of absences is quite similar weather they use high amount of alcohol or not.
Hypothesis 3: There is a relationship between alcohol use and student’s health. Initialise a plot of high_use and health.
g4 <- ggplot(alc, aes(x = high_use, y = health, col = sex))
Define the plot as a boxplot and draw it.
g4 + geom_boxplot() + ggtitle("Student health by alcohol consumption")
For male students, their health score was similar weather they were high users of alcohol or not. For female students, the health score was higher for those students who were high users of alcohol, surprisingly. In high alcohol users there was a lot more variation though.
Hypothesis 4: There is a relationship between alcohol use and student’s quality of family relationships. Initialise a plot of high_use and health.
g4 <- ggplot(alc, aes(x = high_use, y = goout, col = sex))
Define the plot as a boxplot and draw it.
g4 + geom_boxplot() + ggtitle("Going out with friends by alcohol consumption")
Both male and female high alcohol users go out with friends more than low alcohol users.
Find the model with glm().
m <- glm(high_use ~ absences + G3 + health + goout, data = alc, family = "binomial")
Print out a summary of the model.
summary(m)
##
## Call:
## glm(formula = high_use ~ absences + G3 + health + goout, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.8599 -0.7560 -0.5555 0.9414 2.3160
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -3.60300 0.77329 -4.659 3.17e-06 ***
## absences 0.07508 0.02197 3.417 0.000633 ***
## G3 -0.04081 0.03843 -1.062 0.288295
## health 0.12650 0.09087 1.392 0.163897
## goout 0.72684 0.11849 6.134 8.57e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 465.68 on 381 degrees of freedom
## Residual deviance: 398.95 on 377 degrees of freedom
## AIC: 408.95
##
## Number of Fisher Scoring iterations: 4
Print out the coefficients of the model.
coef(m)
## (Intercept) absences G3 health goout
## -3.60300340 0.07507726 -0.04080848 0.12650463 0.72684009
Absences and going out with friends are highly significant predictor of the probability of being a high user of alcohol. Health and grade are not significant predictor of the probability of being a high user of alcohol.
Present and interpret the coefficients of the model as odds ratios and provide confidence intervals for them. Find the model with glm().
m <- glm(high_use ~ absences + G3 + health + goout, data = alc, family = "binomial")
Compute odds ratios (OR).
OR <- coef(m) %>% exp
Compute confidence intervals (CI).
CI <- confint(m) %>% exp
## Waiting for profiling to be done...
Print out the odds ratios with their confidence intervals
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.02724178 0.005694834 0.118851
## absences 1.07796743 1.034131788 1.128425
## G3 0.96001298 0.890279078 1.035492
## health 1.13485470 0.951360927 1.359672
## goout 2.06853388 1.649082084 2.626747
Absences, health, and going out with friends are all positively associated with high use of alcohol whereas grades is negatively associated with high alcohol use. Every absence causes the student 8 % more likely to be a high user of alcohol. For every increase in the health score the student is 13.5% more likely to be a high user of alcohol. Each time the student goes out with friends, they are 107 % more likely to be a high user of alcohol. For every increase in the grade the student is 4 % less likely to be a high user of alcohol.
Fit the model.
m <- glm(high_use ~ absences + goout, data = alc, family = "binomial")
Exploring the predictive power of the model.
Fit the model using only the variables that had a statistical relationship with high/low alcohol consumption.
m <- glm(high_use ~ absences + goout, data = alc, family = "binomial")
Predict() the probability of high_use.
probabilities <- predict(m, type = "response")
Add the predicted probabilities to ‘alc’.
alc <- mutate(alc, probability = probabilities)
Use the probabilities to make a prediction of high_use.
alc <- mutate(alc, prediction = probability > 0.5)
See the last ten original classes, predicted probabilities, and class predictions.
select(alc, failures, absences, sex, high_use, probability, prediction) %>% tail(10)
## failures absences sex high_use probability prediction
## 373 1 0 M FALSE 0.10204808 FALSE
## 374 1 7 M TRUE 0.28913349 FALSE
## 375 0 1 F FALSE 0.20395640 FALSE
## 376 0 6 F FALSE 0.27356268 FALSE
## 377 1 2 F FALSE 0.11705469 FALSE
## 378 0 2 F FALSE 0.36613754 FALSE
## 379 2 2 F FALSE 0.11705469 FALSE
## 380 0 3 F FALSE 0.06419413 FALSE
## 381 0 4 M TRUE 0.58446429 TRUE
## 382 0 2 M TRUE 0.05971939 FALSE
Tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE TRUE
## FALSE 245 23
## TRUE 67 47
23 times the prediction is “high alcohol use” when the variable is not “high alcohol use”. 67 times the prediction is not “high alcohol use” when the variable is “high alcohol use”.
Access dplyr and ggplot2.
library(dplyr); library(ggplot2)
A graphic visualizing both the actual values and the predictions.
Initialize a plot of ‘high_use’ versus ‘probability’ in ‘alc’.
g <- ggplot(alc, aes(x = probability, y = high_use, col = prediction))
Define the geom as points and draw the plot.
g + geom_point()
Tabulate the target variable versus the predictions.
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table %>% addmargins
## prediction
## high_use FALSE TRUE Sum
## FALSE 0.64136126 0.06020942 0.70157068
## TRUE 0.17539267 0.12303665 0.29842932
## Sum 0.81675393 0.18324607 1.00000000
According to the prediction, 82% of all the students are not high alcohol users. According to the actual values 70% of all the students are not high alcohol users. There is a quite big difference between the prediction and the actual model. Compute the total proportion of inaccurately classified individuals (the training error).
Define a loss function (average prediction error).
loss_func <- function(class, prob) {
n_wrong <- abs(class - prob) > 0.5
mean(n_wrong)
}
Call loss_func to compute the average number of wrong predictions in the (training) data.
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.2356021
The training error is about 24%, which shows that the accuracy of the model is about 76%.
#Access the MASS package.
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
#Load the data.
data("Boston")
#Explore the dataset.
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
#Plot matrix of the variables.
pairs(Boston)
There are 506 observations (rows) and 14 variables (columns) in the dataset. The variables are for example crim (per capita crime rate by town), zn (proportion of residential land zoned for lots over 25,000 sq.ft), indus (proportion of non-retail business acres per town), chas (Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)), nox (nitrogen oxides concentration (parts per 10 million)), lstat (lower status of the population (percent)) and medv (median value of owner-occupied homes in $1000s).
For more details of the dataset, please visit https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/Boston.html
library(dplyr)
library(corrplot)
## corrplot 0.84 loaded
#Calculate the correlation matrix and round it.
cor_matrix<-cor(Boston) %>% round(digits = 2)
#Print the correlation matrix.
cor_matrix
## crim zn indus chas nox rm age dis rad tax ptratio
## crim 1.00 -0.20 0.41 -0.06 0.42 -0.22 0.35 -0.38 0.63 0.58 0.29
## zn -0.20 1.00 -0.53 -0.04 -0.52 0.31 -0.57 0.66 -0.31 -0.31 -0.39
## indus 0.41 -0.53 1.00 0.06 0.76 -0.39 0.64 -0.71 0.60 0.72 0.38
## chas -0.06 -0.04 0.06 1.00 0.09 0.09 0.09 -0.10 -0.01 -0.04 -0.12
## nox 0.42 -0.52 0.76 0.09 1.00 -0.30 0.73 -0.77 0.61 0.67 0.19
## rm -0.22 0.31 -0.39 0.09 -0.30 1.00 -0.24 0.21 -0.21 -0.29 -0.36
## age 0.35 -0.57 0.64 0.09 0.73 -0.24 1.00 -0.75 0.46 0.51 0.26
## dis -0.38 0.66 -0.71 -0.10 -0.77 0.21 -0.75 1.00 -0.49 -0.53 -0.23
## rad 0.63 -0.31 0.60 -0.01 0.61 -0.21 0.46 -0.49 1.00 0.91 0.46
## tax 0.58 -0.31 0.72 -0.04 0.67 -0.29 0.51 -0.53 0.91 1.00 0.46
## ptratio 0.29 -0.39 0.38 -0.12 0.19 -0.36 0.26 -0.23 0.46 0.46 1.00
## black -0.39 0.18 -0.36 0.05 -0.38 0.13 -0.27 0.29 -0.44 -0.44 -0.18
## lstat 0.46 -0.41 0.60 -0.05 0.59 -0.61 0.60 -0.50 0.49 0.54 0.37
## medv -0.39 0.36 -0.48 0.18 -0.43 0.70 -0.38 0.25 -0.38 -0.47 -0.51
## black lstat medv
## crim -0.39 0.46 -0.39
## zn 0.18 -0.41 0.36
## indus -0.36 0.60 -0.48
## chas 0.05 -0.05 0.18
## nox -0.38 0.59 -0.43
## rm 0.13 -0.61 0.70
## age -0.27 0.60 -0.38
## dis 0.29 -0.50 0.25
## rad -0.44 0.49 -0.38
## tax -0.44 0.54 -0.47
## ptratio -0.18 0.37 -0.51
## black 1.00 -0.37 0.33
## lstat -0.37 1.00 -0.74
## medv 0.33 -0.74 1.00
#Visualize the correlation matrix.
corrplot(cor_matrix, method="circle", type="upper", cl.pos="b", tl.pos="d", tl.cex = 0.6)
Positive correlations are displayed in blue and negative correlations in red color. Color intensity and the size of the circle are proportional to the correlation coefficients. There is a high negative correlation between indus (proportion of non-retail business acres per town) and dis (weighted mean of distances to five Boston employment centres), nox (nitrogen oxides concentration (parts per 10 million)) and dis (weighted mean of distances to five Boston employment centres), age (proportion of owner-occupied units built prior to 1940) and dis (weighted mean of distances to five Boston employment centres) and istat (lower status of the population (percent)) and medv (median value of owner-occupied homes in $1000s). There is a high positive correlation between rad (index of accessibility to radial highways) and tax (full-value property-tax rate per $10,000).
Standardize the dataset, create a categorical variable of the crime rate, divide the dataset to train and test sets.
#Center and standardize variables.
boston_scaled <- scale(Boston)
#Summaries of the scaled variables.
summary(boston_scaled)
## crim zn indus chas
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563 Min. :-0.2723
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668 1st Qu.:-0.2723
## Median :-0.390280 Median :-0.48724 Median :-0.2109 Median :-0.2723
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150 3rd Qu.:-0.2723
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202 Max. : 3.6648
## nox rm age dis
## Min. :-1.4644 Min. :-3.8764 Min. :-2.3331 Min. :-1.2658
## 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366 1st Qu.:-0.8049
## Median :-0.1441 Median :-0.1084 Median : 0.3171 Median :-0.2790
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059 3rd Qu.: 0.6617
## Max. : 2.7296 Max. : 3.5515 Max. : 1.1164 Max. : 3.9566
## rad tax ptratio black
## Min. :-0.9819 Min. :-1.3127 Min. :-2.7047 Min. :-3.9033
## 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876 1st Qu.: 0.2049
## Median :-0.5225 Median :-0.4642 Median : 0.2746 Median : 0.3808
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058 3rd Qu.: 0.4332
## Max. : 1.6596 Max. : 1.7964 Max. : 1.6372 Max. : 0.4406
## lstat medv
## Min. :-1.5296 Min. :-1.9063
## 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 3.5453 Max. : 2.9865
#Class of the boston_scaled object.
class(boston_scaled)
## [1] "matrix" "array"
#Change the object to data frame.
boston_scaled <- as.data.frame(boston_scaled)
After scaling the mean is 0 for all the variables which means that all variables are normally distributed.
#Summary of the scaled crime rate.
summary(boston_scaled$crim)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.419367 -0.410563 -0.390280 0.000000 0.007389 9.924110
#Create a quantile vector of crim and print it.
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
#Create a categorical variable 'crime'.
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
#Look at the table of the new factor crime.
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
#Remove original crim from the dataset.
boston_scaled <- dplyr::select(boston_scaled, -crim)
#Add the new categorical value to scaled data.
boston_scaled <- data.frame(boston_scaled, crime)
Divide the dataset to train and test sets, so that 80% of the data belongs to the train set.
#Number of rows in the Boston dataset.
n <- nrow(boston_scaled)
#Choose randomly 80% of the rows.
ind <- sample(n, size = n * 0.8)
#Create train set.
train <- boston_scaled[ind,]
#Create test set.
test <- boston_scaled[-ind,]
#Save the correct classes from test data.
correct_classes <- test$crime
#Remove the crime variable from test data.
test <- dplyr::select(test, -crime)
Fit the linear discriminant analysis on the train set.
#Linear discriminant analysis.
lda.fit <- lda(crime ~ ., data = train)
#Print the lda.fit object.
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2524752 0.2425743 0.2500000 0.2549505
##
## Group means:
## zn indus chas nox rm age
## low 1.0048421 -0.9105766 -0.156532002 -0.8801536 0.4489977 -0.8684362
## med_low -0.1103152 -0.3481024 -0.071456607 -0.5615630 -0.1057151 -0.3239847
## med_high -0.3666748 0.1100387 0.195445218 0.3485922 0.1222717 0.3822798
## high -0.4872402 1.0170891 -0.004759149 1.0327604 -0.4416683 0.8010758
## dis rad tax ptratio black lstat
## low 0.8968729 -0.6992582 -0.7305187 -0.44181896 0.37566046 -0.76009248
## med_low 0.3099014 -0.5447506 -0.4806209 -0.04544721 0.32183057 -0.20200821
## med_high -0.3512599 -0.3974038 -0.3313283 -0.29959318 0.05784464 0.02602521
## high -0.8475092 1.6384176 1.5142626 0.78111358 -0.71239933 0.84145452
## medv
## low 0.51311309
## med_low 0.02195121
## med_high 0.18084315
## high -0.67716445
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.09115582 0.73133235 -0.936110630
## indus 0.06216181 -0.20485110 0.147162308
## chas -0.10254699 -0.06233791 0.064299994
## nox 0.35716962 -0.71292262 -1.351513228
## rm -0.08351714 -0.09132134 -0.220284684
## age 0.26456027 -0.27736063 -0.138104130
## dis -0.02787823 -0.25246228 0.001672971
## rad 3.13783346 0.97320353 -0.198641467
## tax 0.06527128 -0.05306499 0.744478953
## ptratio 0.09674306 0.02958248 -0.228132357
## black -0.12539202 0.05910633 0.170729072
## lstat 0.23206895 -0.34306978 0.116105962
## medv 0.19364096 -0.46865080 -0.295612243
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9519 0.0363 0.0117
#The function for lda biplot arrows.
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
#Target classes as numeric.
classes <- as.numeric(train$crime)
#Plot the lda results.
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1)
The best linear separator is variable index of accessibility to radial highways (rad), which has the longest arrow in the picture. The second best separator is difficult to make out, but it looks like it would be nitrogen oxides concentration (parts per 10 million) (nox).
Predicting with the model.
#Predict classes with test data.
lda.pred <- predict(lda.fit, newdata = test)
#Cross tabulate the results.
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 14 10 1 0
## med_low 6 17 5 0
## med_high 0 8 16 1
## high 0 0 0 24
Note that the numbers change every time you run the model. The model predicted the high crime rates well (32/32 were classified correctly). Other categories the model did not predict as well: For medium high crime rates, 17/29 were classified correctly, for medium low crime rates 17/25 were classified correctly, and for low crime rates 9/16 were classified correctly.
total <- c(9+5+2+3+17+5+10+17+2+32)
total
## [1] 102
correct <- c(9+17+17+32)
correct
## [1] 75
Out of a total of 102 observations, 75 observations were classified correctly.
ratio <- c(correct/total)
ratio
## [1] 0.7352941
Accuracy of the model was 74%, which is not that bad but could be better.
Reload Boston dataset.
library(MASS)
data("Boston")
#Center and standardize variables.
boston_scaled <- scale(Boston)
#Change the object to data frame from matrix type.
boston_scaled <- as.data.frame(boston_scaled)
#Calculate the Euclidean distances between observations.
dist_eu <- dist(boston_scaled)
#Look at the summary of the distances.
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
Run k-means algorithm on the dataset.
#K-means clustering.
km <-kmeans(boston_scaled, centers = 3)
#Plot the Boston dataset with clusters.
pairs(boston_scaled, col = km$cluster)
#Investigate the optimal number of clusters and run the algorithm again.
set.seed(123)
#Determine the number of clusters.
k_max <- 10
#Calculate the total within sum of squares.
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled, k)$tot.withinss})
#Visualize the results with qplot. Visualize (with qplot) the total WCSS when the number of cluster goes from 1 to 10.
library(ggplot2)
qplot(x = 1:k_max, y = twcss, geom = 'line')
2 clusters seems optimal as the bend (knee) is at 2.
#Run kmeans() again with two clusters.
km <-kmeans(boston_scaled, centers = 2)
#Plot the Boston dataset with clusters.
pairs(boston_scaled, col = km$cluster)
Like observed before, the optimal number of clusters seems to be two.
Super bonus.
model_predictors <- dplyr::select(train, -crime)
#Check the dimensions.
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
#Matrix multiplication.
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
#Matrix multiplication.
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
#Create a 3D plot of the columns of the matrix product by typing the code below.
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
## Warning: `arrange_()` is deprecated as of dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.
#Add argument color as an argument in the plot_ly() function.
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)
Draw another 3D plot where the color is defined by the clusters of the k-means.
#Make a k-means with 4 clusters to compare the methods.
km3D <-kmeans(boston_scaled, centers = 4)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = km3D$cluster[ind])
Medium high crime rates seems to bee better defined than cluster 1. Cluster 2 is a bit better defined (not so much intermingling) than low crime rate in the first picture. Cluster 3 is quite similar with high crime rates, even though cluster 3 is a bit more better defined. Cluster 4 is more defined than medium low crime rates in the first picture.
#Read the data and show summaries of the variables.
human<-read.table(file = "human.txt", sep="\t", header=TRUE)
str(human)
## 'data.frame': 155 obs. of 8 variables:
## $ Edu2.FM : num 1.007 0.997 0.983 0.989 0.969 ...
## $ Labo.FM : num 0.891 0.819 0.825 0.884 0.829 ...
## $ Edu.Exp : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ Life.Exp : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ GNI : int 64992 42261 56431 44025 45435 43919 39568 52947 42155 32689 ...
## $ Mat.Mor : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Ado.Birth: num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Parli.F : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
summary(human)
## Edu2.FM Labo.FM Edu.Exp Life.Exp
## Min. :0.1717 Min. :0.1857 Min. : 5.40 Min. :49.00
## 1st Qu.:0.7264 1st Qu.:0.5984 1st Qu.:11.25 1st Qu.:66.30
## Median :0.9375 Median :0.7535 Median :13.50 Median :74.20
## Mean :0.8529 Mean :0.7074 Mean :13.18 Mean :71.65
## 3rd Qu.:0.9968 3rd Qu.:0.8535 3rd Qu.:15.20 3rd Qu.:77.25
## Max. :1.4967 Max. :1.0380 Max. :20.20 Max. :83.50
## GNI Mat.Mor Ado.Birth Parli.F
## Min. : 581 Min. : 1.0 Min. : 0.60 Min. : 0.00
## 1st Qu.: 4198 1st Qu.: 11.5 1st Qu.: 12.65 1st Qu.:12.40
## Median : 12040 Median : 49.0 Median : 33.60 Median :19.30
## Mean : 17628 Mean : 149.1 Mean : 47.16 Mean :20.91
## 3rd Qu.: 24512 3rd Qu.: 190.0 3rd Qu.: 71.95 3rd Qu.:27.95
## Max. :123124 Max. :1100.0 Max. :204.80 Max. :57.50
There are 8 variables and 155 observations.
#Access GGally.
library(GGally)
#Visualize the variables.
ggpairs(human)
Many of the variables are skewed to either side and/or have long tails. Education expectancy looks the most normally distributed. Mean education expectancy for example is 13.2 years, mean life expectancy 71.7 years and mean adolescent birth rate 47.2. There is great variation within some variables: For the Gross national income per capita, the minimum value is 581, median 12040 and maximum 123124 and for the Maternal mortality ratio, the minimum value is 1, median 49 and maximum 1100. Then, in the Education expectancy variation is relatively small as the minimum value is 5.4, median 13.5 and maximum value 20.2.
There are several variables that are highly correlated with each other, for example: Adolescent birth rate and Maternal mortality, Life expectancy and Education expectancy, Life expectancy and Adolescent birth rate, Education expectancy and Maternal mortality.
Percentage of female representatives in parliament and Adolescent birth rate, for example, are not correlated.
#Perform principal component analysis on the non-standardized data.
pca_human <- prcomp(human)
#Create and print out a summary of pca_human.
s <- summary(pca_human)
s
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## Standard deviation 1.854e+04 185.5219 25.19 11.45 3.766 1.566 0.1912 0.1591
## Proportion of Variance 9.999e-01 0.0001 0.00 0.00 0.000 0.000 0.0000 0.0000
## Cumulative Proportion 9.999e-01 1.0000 1.00 1.00 1.000 1.000 1.0000 1.0000
# Rounded percetanges of variance captured by each PC.
pca_pr <- round(1*s$importance[2,]*100, digits = 1)
#Print out the percentages of variance.
pca_pr
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 100 0 0 0 0 0 0 0
#Create object pc_lab to be used as axis labels.
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
#Draw a biplot.
biplot(pca_human, cex = c(0.8, 0.1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
#Standardize the variables.
human_std <- scale(human)
#Print out summaries of the standardized variables.
summary(human_std)
## Edu2.FM Labo.FM Edu.Exp Life.Exp
## Min. :-2.8189 Min. :-2.6247 Min. :-2.7378 Min. :-2.7188
## 1st Qu.:-0.5233 1st Qu.:-0.5484 1st Qu.:-0.6782 1st Qu.:-0.6425
## Median : 0.3503 Median : 0.2316 Median : 0.1140 Median : 0.3056
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5958 3rd Qu.: 0.7350 3rd Qu.: 0.7126 3rd Qu.: 0.6717
## Max. : 2.6646 Max. : 1.6632 Max. : 2.4730 Max. : 1.4218
## GNI Mat.Mor Ado.Birth Parli.F
## Min. :-0.9193 Min. :-0.6992 Min. :-1.1325 Min. :-1.8203
## 1st Qu.:-0.7243 1st Qu.:-0.6496 1st Qu.:-0.8394 1st Qu.:-0.7409
## Median :-0.3013 Median :-0.4726 Median :-0.3298 Median :-0.1403
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.3712 3rd Qu.: 0.1932 3rd Qu.: 0.6030 3rd Qu.: 0.6127
## Max. : 5.6890 Max. : 4.4899 Max. : 3.8344 Max. : 3.1850
#Perform principal component analysis (with the SVD method).
pca_human <- prcomp(human_std)
#Create and print out a summary of pca_human.
s <- summary(pca_human)
s
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6 PC7
## Standard deviation 2.0708 1.1397 0.87505 0.77886 0.66196 0.53631 0.45900
## Proportion of Variance 0.5361 0.1624 0.09571 0.07583 0.05477 0.03595 0.02634
## Cumulative Proportion 0.5361 0.6984 0.79413 0.86996 0.92473 0.96069 0.98702
## PC8
## Standard deviation 0.32224
## Proportion of Variance 0.01298
## Cumulative Proportion 1.00000
#Rounded percetanges of variance captured by each PC.
pca_pr <- round(1*s$importance[2,]*100, digits = 1)
#Print out the percentages of variance.
pca_pr
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 53.6 16.2 9.6 7.6 5.5 3.6 2.6 1.3
#Create object pc_lab to be used as axis labels.
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
#Draw a biplot.
biplot(pca_human, choices = 1:2, cex = c(0.6, 1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2], main = "Global health and equality related indicators")
In the non-standardized data, the first principal component PC1 explains 100% of the variance and the second principal component PC2 explains 0% of the variance. In the standardized data, PC1 explains 53.6% of the variance and PC2 explains 16.2% of the variance. Together they explain 69.8% of the variance of the whole dataset. In PCA, the principal components are constructed so, that the first principal component accounts for the largest possible variance in the data set and the second one the second largest possible variance.
In the non-standardized data, there were variables with high range (great variance), which dominated the ones with smaller range, which lead to biased results. Standardization standardizes the variables so that every one of them contributes equally to the analysis, which prevents the problem of variables with larger range dominating and causing biased results.
In the non-standardized data, for example Gross national income GNI had such a big variance that it caused biased results. After standardization and removing the domination problem, the effects of the variables with smaller variation, for example education expectancy, can be seen.
Iceland, Sweden, Norway, Finland and Denmark are closely grouped together and are therefore similar to each other. They all have quite high Percentage of female representatives in parliament, Expected years of education, Gross national income per capita, Population with secondary Education female to male ratio and life expectancy at birth.
The arrows visualize the connections between the original variables and the principal components. Expected years of education, Gross national income per capita, Population with secondary education female to male ratio and Life expectancy at birth have a small angle between them, so we can assume correlation between them. Maternal mortality ratio and adolescent birth rate also seem to be correlated. The angle of the arrows for Percentage of female representatives in parliament and Adolescent birth rate for example is quite large and therefore we can assume that the is no correlation between those variables.
Expected years of education, Gross national income per capita, Population with secondary education female to male ratio, Life expectancy at birth, Maternal mortality ratio and Adolescent birth rate all have a small angle with the principal component 1 and can be assumed to correlate with each other. Percentage of female representatives in parliament and Labour force participation rate female/male ratio on the other hand, can be assumed to correlate with principal component 2.
Sierra Leone, Liberia, Congo and Chad for example seem to have both high Maternal mortality ratio and Adolescent birth rate and do not have high Expected years of education, Gross national income per capita or life expectancy at birth. Mosambique has both quite high Maternal mortality ratio and Adolescent birth rate but women also have a high Labour force participation rate.
#Load library and tea dataset.
library(FactoMineR)
data(tea)
#Explore tea dataset.
dim(tea)
## [1] 300 36
str(tea)
## 'data.frame': 300 obs. of 36 variables:
## $ breakfast : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
## $ tea.time : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
## $ evening : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
## $ lunch : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ dinner : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
## $ always : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
## $ home : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
## $ work : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
## $ tearoom : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
## $ friends : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
## $ resto : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
## $ pub : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ sugar : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ where : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ price : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
## $ age : int 39 45 47 23 48 21 37 36 40 37 ...
## $ sex : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
## $ SPC : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
## $ Sport : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
## $ age_Q : Factor w/ 5 levels "15-24","25-34",..: 3 4 4 1 4 1 3 3 3 3 ...
## $ frequency : Factor w/ 4 levels "1/day","1 to 2/week",..: 1 1 3 1 3 1 4 2 3 3 ...
## $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
## $ spirituality : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
## $ healthy : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
## $ diuretic : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
## $ friendliness : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
## $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
## $ feminine : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
## $ sophisticated : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
## $ slimming : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ exciting : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
## $ relaxing : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
## $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...
summary(tea)
## breakfast tea.time evening lunch
## breakfast :144 Not.tea time:131 evening :103 lunch : 44
## Not.breakfast:156 tea time :169 Not.evening:197 Not.lunch:256
##
##
##
##
##
## dinner always home work
## dinner : 21 always :103 home :291 Not.work:213
## Not.dinner:279 Not.always:197 Not.home: 9 work : 87
##
##
##
##
##
## tearoom friends resto pub
## Not.tearoom:242 friends :196 Not.resto:221 Not.pub:237
## tearoom : 58 Not.friends:104 resto : 79 pub : 63
##
##
##
##
##
## Tea How sugar how
## black : 74 alone:195 No.sugar:155 tea bag :170
## Earl Grey:193 lemon: 33 sugar :145 tea bag+unpackaged: 94
## green : 33 milk : 63 unpackaged : 36
## other: 9
##
##
##
## where price age sex
## chain store :192 p_branded : 95 Min. :15.00 F:178
## chain store+tea shop: 78 p_cheap : 7 1st Qu.:23.00 M:122
## tea shop : 30 p_private label: 21 Median :32.00
## p_unknown : 12 Mean :37.05
## p_upscale : 53 3rd Qu.:48.00
## p_variable :112 Max. :90.00
##
## SPC Sport age_Q frequency
## employee :59 Not.sportsman:121 15-24:92 1/day : 95
## middle :40 sportsman :179 25-34:69 1 to 2/week: 44
## non-worker :64 35-44:40 +2/day :127
## other worker:20 45-59:61 3 to 6/week: 34
## senior :35 +60 :38
## student :70
## workman :12
## escape.exoticism spirituality healthy
## escape-exoticism :142 Not.spirituality:206 healthy :210
## Not.escape-exoticism:158 spirituality : 94 Not.healthy: 90
##
##
##
##
##
## diuretic friendliness iron.absorption
## diuretic :174 friendliness :242 iron absorption : 31
## Not.diuretic:126 Not.friendliness: 58 Not.iron absorption:269
##
##
##
##
##
## feminine sophisticated slimming exciting
## feminine :129 Not.sophisticated: 85 No.slimming:255 exciting :116
## Not.feminine:171 sophisticated :215 slimming : 45 No.exciting:184
##
##
##
##
##
## relaxing effect.on.health
## No.relaxing:113 effect on health : 66
## relaxing :187 No.effect on health:234
##
##
##
##
##
There are 36 variables and 300 observations. All the variables are factorial, except age, which is integral.
#Access library dplyr.
library(dplyr)
library(tidyr)
#Column names to keep in the dataset.
keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch")
#Select the 'keep_columns' to create a new dataset.
tea_time <- dplyr::select(tea, one_of(keep_columns))
#Look at the summaries and structure of the data.
str(tea_time)
## 'data.frame': 300 obs. of 6 variables:
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ sugar: Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ where: Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ lunch: Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
summary(tea)
## breakfast tea.time evening lunch
## breakfast :144 Not.tea time:131 evening :103 lunch : 44
## Not.breakfast:156 tea time :169 Not.evening:197 Not.lunch:256
##
##
##
##
##
## dinner always home work
## dinner : 21 always :103 home :291 Not.work:213
## Not.dinner:279 Not.always:197 Not.home: 9 work : 87
##
##
##
##
##
## tearoom friends resto pub
## Not.tearoom:242 friends :196 Not.resto:221 Not.pub:237
## tearoom : 58 Not.friends:104 resto : 79 pub : 63
##
##
##
##
##
## Tea How sugar how
## black : 74 alone:195 No.sugar:155 tea bag :170
## Earl Grey:193 lemon: 33 sugar :145 tea bag+unpackaged: 94
## green : 33 milk : 63 unpackaged : 36
## other: 9
##
##
##
## where price age sex
## chain store :192 p_branded : 95 Min. :15.00 F:178
## chain store+tea shop: 78 p_cheap : 7 1st Qu.:23.00 M:122
## tea shop : 30 p_private label: 21 Median :32.00
## p_unknown : 12 Mean :37.05
## p_upscale : 53 3rd Qu.:48.00
## p_variable :112 Max. :90.00
##
## SPC Sport age_Q frequency
## employee :59 Not.sportsman:121 15-24:92 1/day : 95
## middle :40 sportsman :179 25-34:69 1 to 2/week: 44
## non-worker :64 35-44:40 +2/day :127
## other worker:20 45-59:61 3 to 6/week: 34
## senior :35 +60 :38
## student :70
## workman :12
## escape.exoticism spirituality healthy
## escape-exoticism :142 Not.spirituality:206 healthy :210
## Not.escape-exoticism:158 spirituality : 94 Not.healthy: 90
##
##
##
##
##
## diuretic friendliness iron.absorption
## diuretic :174 friendliness :242 iron absorption : 31
## Not.diuretic:126 Not.friendliness: 58 Not.iron absorption:269
##
##
##
##
##
## feminine sophisticated slimming exciting
## feminine :129 Not.sophisticated: 85 No.slimming:255 exciting :116
## Not.feminine:171 sophisticated :215 slimming : 45 No.exciting:184
##
##
##
##
##
## relaxing effect.on.health
## No.relaxing:113 effect on health : 66
## relaxing :187 No.effect on health:234
##
##
##
##
##
There are now 6 variables and 300 observations.
#Multiple correspondence analysis.
mca <- MCA(tea_time, graph = FALSE)
#Summary of the model.
summary(mca)
##
## Call:
## MCA(X = tea_time, graph = FALSE)
##
##
## Eigenvalues
## Dim.1 Dim.2 Dim.3 Dim.4 Dim.5 Dim.6 Dim.7
## Variance 0.279 0.261 0.219 0.189 0.177 0.156 0.144
## % of var. 15.238 14.232 11.964 10.333 9.667 8.519 7.841
## Cumulative % of var. 15.238 29.471 41.435 51.768 61.434 69.953 77.794
## Dim.8 Dim.9 Dim.10 Dim.11
## Variance 0.141 0.117 0.087 0.062
## % of var. 7.705 6.392 4.724 3.385
## Cumulative % of var. 85.500 91.891 96.615 100.000
##
## Individuals (the 10 first)
## Dim.1 ctr cos2 Dim.2 ctr cos2 Dim.3
## 1 | -0.298 0.106 0.086 | -0.328 0.137 0.105 | -0.327
## 2 | -0.237 0.067 0.036 | -0.136 0.024 0.012 | -0.695
## 3 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 4 | -0.530 0.335 0.460 | -0.318 0.129 0.166 | 0.211
## 5 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 6 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 7 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 8 | -0.237 0.067 0.036 | -0.136 0.024 0.012 | -0.695
## 9 | 0.143 0.024 0.012 | 0.871 0.969 0.435 | -0.067
## 10 | 0.476 0.271 0.140 | 0.687 0.604 0.291 | -0.650
## ctr cos2
## 1 0.163 0.104 |
## 2 0.735 0.314 |
## 3 0.062 0.069 |
## 4 0.068 0.073 |
## 5 0.062 0.069 |
## 6 0.062 0.069 |
## 7 0.062 0.069 |
## 8 0.735 0.314 |
## 9 0.007 0.003 |
## 10 0.643 0.261 |
##
## Categories (the 10 first)
## Dim.1 ctr cos2 v.test Dim.2 ctr cos2
## black | 0.473 3.288 0.073 4.677 | 0.094 0.139 0.003
## Earl Grey | -0.264 2.680 0.126 -6.137 | 0.123 0.626 0.027
## green | 0.486 1.547 0.029 2.952 | -0.933 6.111 0.107
## alone | -0.018 0.012 0.001 -0.418 | -0.262 2.841 0.127
## lemon | 0.669 2.938 0.055 4.068 | 0.531 1.979 0.035
## milk | -0.337 1.420 0.030 -3.002 | 0.272 0.990 0.020
## other | 0.288 0.148 0.003 0.876 | 1.820 6.347 0.102
## tea bag | -0.608 12.499 0.483 -12.023 | -0.351 4.459 0.161
## tea bag+unpackaged | 0.350 2.289 0.056 4.088 | 1.024 20.968 0.478
## unpackaged | 1.958 27.432 0.523 12.499 | -1.015 7.898 0.141
## v.test Dim.3 ctr cos2 v.test
## black 0.929 | -1.081 21.888 0.382 -10.692 |
## Earl Grey 2.867 | 0.433 9.160 0.338 10.053 |
## green -5.669 | -0.108 0.098 0.001 -0.659 |
## alone -6.164 | -0.113 0.627 0.024 -2.655 |
## lemon 3.226 | 1.329 14.771 0.218 8.081 |
## milk 2.422 | 0.013 0.003 0.000 0.116 |
## other 5.534 | -2.524 14.526 0.197 -7.676 |
## tea bag -6.941 | -0.065 0.183 0.006 -1.287 |
## tea bag+unpackaged 11.956 | 0.019 0.009 0.000 0.226 |
## unpackaged -6.482 | 0.257 0.602 0.009 1.640 |
##
## Categorical variables (eta2)
## Dim.1 Dim.2 Dim.3
## Tea | 0.126 0.108 0.410 |
## How | 0.076 0.190 0.394 |
## how | 0.708 0.522 0.010 |
## sugar | 0.065 0.001 0.336 |
## where | 0.702 0.681 0.055 |
## lunch | 0.000 0.064 0.111 |
#Visualize the dataset.
gather(tea_time) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
## Warning: attributes are not identical across measure variables;
## they will be dropped
#Visualize Multiple Correspondence Analysis.
plot(mca, invisible=c("ind"), habillage="quali")
People who drink unpackaged tea buy it from tea shops and people who use tea bags for theit tea buy it from the chain stores. People who drink both unpackaged tea and use tea bags also buy their tea from both types of shops.
#Read the data and explore dimensions.
RATSL<-read.table(file = "RATSL.txt", sep="\t", header=TRUE)
dim(RATSL)
## [1] 176 5
str(RATSL)
## 'data.frame': 176 obs. of 5 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Group : int 1 1 1 1 1 1 1 1 2 2 ...
## $ WD : chr "WD1" "WD1" "WD1" "WD1" ...
## $ Weight: int 240 225 245 260 255 260 275 245 410 405 ...
## $ Time : int 1 1 1 1 1 1 1 1 1 1 ...
summary(RATSL)
## ID Group WD Weight
## Min. : 1.00 Min. :1.00 Length:176 Min. :225.0
## 1st Qu.: 4.75 1st Qu.:1.00 Class :character 1st Qu.:267.0
## Median : 8.50 Median :1.50 Mode :character Median :344.5
## Mean : 8.50 Mean :1.75 Mean :384.5
## 3rd Qu.:12.25 3rd Qu.:2.25 3rd Qu.:511.2
## Max. :16.00 Max. :3.00 Max. :628.0
## Time
## Min. : 1.00
## 1st Qu.:15.00
## Median :36.00
## Mean :33.55
## 3rd Qu.:50.00
## Max. :64.00
#Change the categorical variables to factors.
RATSL$ID <- factor(RATSL$ID)
RATSL$Group <- factor(RATSL$Group)
dim(RATSL)
## [1] 176 5
str(RATSL)
## 'data.frame': 176 obs. of 5 variables:
## $ ID : Factor w/ 16 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ Group : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 2 2 ...
## $ WD : chr "WD1" "WD1" "WD1" "WD1" ...
## $ Weight: int 240 225 245 260 255 260 275 245 410 405 ...
## $ Time : int 1 1 1 1 1 1 1 1 1 1 ...
summary(RATSL)
## ID Group WD Weight Time
## 1 : 11 1:88 Length:176 Min. :225.0 Min. : 1.00
## 2 : 11 2:44 Class :character 1st Qu.:267.0 1st Qu.:15.00
## 3 : 11 3:44 Mode :character Median :344.5 Median :36.00
## 4 : 11 Mean :384.5 Mean :33.55
## 5 : 11 3rd Qu.:511.2 3rd Qu.:50.00
## 6 : 11 Max. :628.0 Max. :64.00
## (Other):110
There are 176 observations and 5 variables. The variables are ID, Group, WD, Weight and Time. Data was converted to long form in the data wrangling exercise. Rat’s weights have been measured several times on various weekdays.
#Plot the rat weights.
library("tidyverse")
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ tibble 3.0.4 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.0
## ✓ purrr 0.3.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x plotly::filter() masks dplyr::filter(), stats::filter()
## x dplyr::lag() masks stats::lag()
## x plotly::select() masks MASS::select(), dplyr::select()
ggplot(RATSL, aes(x = Time, y = Weight, linetype = ID))+
geom_line() + scale_linetype_manual(values = rep(1:10, times=4))+
facet_grid(. ~ Group, labeller = label_both)+
theme_bw() + theme(legend.position = "none")+
theme(panel.grid.minor.y = element_blank()) +
scale_y_continuous(limits = c(min(RATSL$Weight), max(RATSL$Weight)))
The plot shows 3 different groups and the rat’s weight change over time. In group 1, the weight of the rats is lower than in the other groups. The weights of the rats is highest in the group 3. All groups seem to have an outlier, in group 2 the “biggest” one. In all groups the weight of the rats increases during the experiment. There also seems to be tracking as rats who have high weight in the beginning of the experiment, have high weight at the end of the experiment.
#Standardize the variable weight.
RATSL <- RATSL %>%
group_by(Time) %>%
mutate(stdweight = Weight) %>%
ungroup()
#Glimpse the data and check the structure.
glimpse(RATSL)
## Rows: 176
## Columns: 6
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2…
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1,…
## $ WD <chr> "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD…
## $ Weight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445, 555,…
## $ Time <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, 8,…
## $ stdweight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445, 555,…
str(RATSL)
## tibble [176 × 6] (S3: tbl_df/tbl/data.frame)
## $ ID : Factor w/ 16 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ Group : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 2 2 ...
## $ WD : chr [1:176] "WD1" "WD1" "WD1" "WD1" ...
## $ Weight : int [1:176] 240 225 245 260 255 260 275 245 410 405 ...
## $ Time : int [1:176] 1 1 1 1 1 1 1 1 1 1 ...
## $ stdweight: int [1:176] 240 225 245 260 255 260 275 245 410 405 ...
summary(RATSL)
## ID Group WD Weight Time
## 1 : 11 1:88 Length:176 Min. :225.0 Min. : 1.00
## 2 : 11 2:44 Class :character 1st Qu.:267.0 1st Qu.:15.00
## 3 : 11 3:44 Mode :character Median :344.5 Median :36.00
## 4 : 11 Mean :384.5 Mean :33.55
## 5 : 11 3rd Qu.:511.2 3rd Qu.:50.00
## 6 : 11 Max. :628.0 Max. :64.00
## (Other):110
## stdweight
## Min. :225.0
## 1st Qu.:267.0
## Median :344.5
## Mean :384.5
## 3rd Qu.:511.2
## Max. :628.0
##
#Plot the standardized rat weights.
ggplot(RATSL, aes(x = Time, y = stdweight, linetype = ID)) +
geom_line() + scale_linetype_manual(values = rep(1:10, times=4))+
facet_grid(. ~ Group, labeller = label_both)+
theme_bw() + theme(legend.position = "none")+
theme(panel.grid.minor.y = element_blank())+
scale_y_continuous(name = "Standardized weight")
The plot shows 3 different groups and the rat’s weight change over time after standardization.
#Number of weeks, baseline (week 0) included.
n <- RATSL$Time %>% unique() %>% length()
#Summary data with mean and standard error of weight by group and time.
RATSS <- RATSL %>%
group_by(Group, Time) %>%
summarise(mean = mean(Weight), sd = sd(Weight)) %>%
ungroup()
## `summarise()` regrouping output by 'Group' (override with `.groups` argument)
# Glimpse the data
glimpse(RATSS)
## Rows: 33
## Columns: 4
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, …
## $ Time <int> 1, 8, 15, 22, 29, 36, 43, 44, 50, 57, 64, 1, 8, 15, 22, 29, 36,…
## $ mean <dbl> 250.625, 255.000, 254.375, 261.875, 264.625, 265.000, 267.375, …
## $ sd <dbl> 15.22158, 13.09307, 11.47591, 13.60081, 11.05748, 11.78377, 10.…
#Plot the mean profiles.
ggplot(RATSS, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
geom_line() +
scale_linetype_manual(values = c(1,2,3)) +
geom_point(size=3) +
scale_shape_manual(values = c(1,2,3)) +
#geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) +
theme(legend.position = c(0.8,0.8)) +
scale_y_continuous(name = "mean(Weight) +/- se(Weight)")
The plot shows 3 groups and the mean weight change over time. There is no overlap in the mean profiles of the three groups, which suggests that there is a difference between the three groups with respect to the mean weight values.
#Create a summary data by Group and ID with mean as the summary variable (ignoring baseline time 1).
RATSL8S <- RATSL %>%
filter(Time > 1) %>%
group_by(Group, ID) %>%
summarise( mean=mean(Weight) ) %>%
ungroup()
## `summarise()` regrouping output by 'Group' (override with `.groups` argument)
#Glimpse the data.
glimpse(RATSL8S)
## Rows: 16
## Columns: 3
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
## $ mean <dbl> 263.2, 238.9, 261.7, 267.2, 270.9, 276.2, 274.6, 267.5, 443.9, …
#Draw a boxplot of the mean versus treatment.
library(dplyr)
ggplot(RATSL8S, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), weeks 1-8")
We can see one outlier in each group. In group 2, the outlier is furthest distance from the other values. In groups 1 and 3 the sistance of the outlier from other values is not as great.
#Create a new data by filtering the outlier and adjust the ggplot code the draw the plot again with the new data.
#Draw a boxplot of the mean versus treatment.
#Find the numerical values for the outliers.
RATSL8S$mean
## [1] 263.2 238.9 261.7 267.2 270.9 276.2 274.6 267.5 443.9 457.5 455.8 594.0
## [13] 495.2 536.4 542.2 536.2
#Filter the outliers.
RATSL8S1 <- filter(RATSL8S, mean != 238.9, mean != 594.0, mean != 495.2)
RATSL8S1$mean
## [1] 263.2 261.7 267.2 270.9 276.2 274.6 267.5 443.9 457.5 455.8 536.4 542.2
## [13] 536.2
#Create a boxplot.
ggplot(RATSL8S1, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(weight), weeks 1-8")
After the outliers are removed, the variation inside the groups decreases notably, which can be seen from the picture. As there are three groups instead of two, t-test cannot be used.
#Add the baseline from the original data as a new variable to the summary data.
RATSL8S2 <- RATSL8S %>%
mutate(baseline = filter(RATSL, Time==1)$Weight)
#Fit the linear model with the mean as the response.
fit <- lm (mean ~ Group, data = RATSL8S2)
summary(fit)
##
## Call:
## lm(formula = mean ~ Group, data = RATSL8S2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -43.900 -27.169 2.325 9.069 106.200
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 265.02 12.98 20.419 2.92e-11 ***
## Group2 222.77 22.48 9.909 2.00e-07 ***
## Group3 262.48 22.48 11.675 2.90e-08 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 36.71 on 13 degrees of freedom
## Multiple R-squared: 0.9316, Adjusted R-squared: 0.9211
## F-statistic: 88.52 on 2 and 13 DF, p-value: 2.679e-08
#Compute the analysis of variance table for the fitted model with anova().
anova(fit)
## Analysis of Variance Table
##
## Response: mean
## Df Sum Sq Mean Sq F value Pr(>F)
## Group 2 238620 119310 88.525 2.679e-08 ***
## Residuals 13 17521 1348
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
There is a statistically significant difference (p<0.001) between groups 2 and group 3 compared with group 1.
#Read the data and explore dimensions.
BPRSL<-read.table(file = "BPRSL.txt", sep="\t", header=TRUE)
dim(BPRSL)
## [1] 360 5
str(BPRSL)
## 'data.frame': 360 obs. of 5 variables:
## $ treatment: int 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : int 1 2 3 4 5 6 7 8 9 10 ...
## $ weeks : chr "week0" "week0" "week0" "week0" ...
## $ bprs : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week : int 0 0 0 0 0 0 0 0 0 0 ...
summary(BPRSL)
## treatment subject weeks bprs week
## Min. :1.0 Min. : 1.00 Length:360 Min. :18.00 Min. :0
## 1st Qu.:1.0 1st Qu.: 5.75 Class :character 1st Qu.:27.00 1st Qu.:2
## Median :1.5 Median :10.50 Mode :character Median :35.00 Median :4
## Mean :1.5 Mean :10.50 Mean :37.66 Mean :4
## 3rd Qu.:2.0 3rd Qu.:15.25 3rd Qu.:43.00 3rd Qu.:6
## Max. :2.0 Max. :20.00 Max. :95.00 Max. :8
#Change the categorical variables to factors.
BPRSL$treatment <- factor(BPRSL$treatment)
BPRSL$subject <- factor(BPRSL$subject)
dim(BPRSL)
## [1] 360 5
str(BPRSL)
## 'data.frame': 360 obs. of 5 variables:
## $ treatment: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : Factor w/ 20 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ weeks : chr "week0" "week0" "week0" "week0" ...
## $ bprs : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week : int 0 0 0 0 0 0 0 0 0 0 ...
summary(BPRSL)
## treatment subject weeks bprs week
## 1:180 1 : 18 Length:360 Min. :18.00 Min. :0
## 2:180 2 : 18 Class :character 1st Qu.:27.00 1st Qu.:2
## 3 : 18 Mode :character Median :35.00 Median :4
## 4 : 18 Mean :37.66 Mean :4
## 5 : 18 3rd Qu.:43.00 3rd Qu.:6
## 6 : 18 Max. :95.00 Max. :8
## (Other):252
#Glimpse the data.
glimpse(BPRSL)
## Rows: 360
## Columns: 5
## $ treatment <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
## $ subject <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, …
## $ weeks <chr> "week0", "week0", "week0", "week0", "week0", "week0", "week…
## $ bprs <int> 42, 58, 54, 55, 72, 48, 71, 30, 41, 57, 30, 55, 36, 38, 66,…
## $ week <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,…
There are 360 observations and 5 variables. The variables are treatments, subject, weeks, bprs and week. Data was converted to long form in the data wrangling exercise.
#Plot the BPRSL data.
ggplot(BPRSL, aes(x = week, y = bprs, linetype = as.factor(subject))) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
theme(legend.position = "top") +
scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))
#Create a regression model.
BPRS_reg <- lm(bprs ~ week + treatment, data = BPRSL)
#Print out a summary of the model.
summary(BPRS_reg)
##
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
##
## Residuals:
## Min 1Q Median 3Q Max
## -22.454 -8.965 -3.196 7.002 50.244
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 46.4539 1.3670 33.982 <2e-16 ***
## week -2.2704 0.2524 -8.995 <2e-16 ***
## treatment2 0.5722 1.3034 0.439 0.661
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared: 0.1851, Adjusted R-squared: 0.1806
## F-statistic: 40.55 on 2 and 357 DF, p-value: < 2.2e-16
In the linear regression model bprs (brief psychiatric rating scale) is dependent variable and week and treatment are explanatory variables. Variable “treatment” is not statistically significant. It does not have an impact on the model. Variable "week is statistically significant (p<0.001).
library("lme4")
## Loading required package: Matrix
##
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
#Create a random intercept model.
BPRS_ref <- lmer(bprs ~ week + treatment + (1 | subject), data = BPRSL, REML = FALSE)
#Print the summary of the model.
summary(BPRS_ref)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (1 | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2748.7 2768.1 -1369.4 2738.7 355
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0481 -0.6749 -0.1361 0.4813 3.4855
##
## Random effects:
## Groups Name Variance Std.Dev.
## subject (Intercept) 47.41 6.885
## Residual 104.21 10.208
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 1.9090 24.334
## week -2.2704 0.2084 -10.896
## treatment2 0.5722 1.0761 0.532
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.437
## treatment2 -0.282 0.000
In this model too the bprs (brief psychiatric rating scale) is dependent variable and week and treatment are explanatory variables. Random effect is subject. The random intercept model gives different random intercept value for each observation. The linear regression model assumes independence of the repeated measures of bprs rating, which the random intercept model does not. Compared with the linear regression model, the random intercept model gives lower standard errors for the explanatory variables.
BPRS_ref1 <- lmer(bprs ~ week + treatment + (week | subject), data = BPRSL, REML = FALSE)
summary(BPRS_ref1)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2745.4 2772.6 -1365.7 2731.4 353
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -2.8919 -0.6194 -0.0691 0.5531 3.7976
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.8222 8.0512
## week 0.9609 0.9802 -0.51
## Residual 97.4305 9.8707
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 2.1052 22.066
## week -2.2704 0.2977 -7.626
## treatment2 0.5722 1.0405 0.550
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.582
## treatment2 -0.247 0.000
#Perform an ANOVA test on the two models.
anova(BPRS_ref1, BPRS_ref)
## Data: BPRSL
## Models:
## BPRS_ref: bprs ~ week + treatment + (1 | subject)
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_ref 5 2748.7 2768.1 -1369.4 2738.7
## BPRS_ref1 7 2745.4 2772.6 -1365.7 2731.4 7.2721 2 0.02636 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
In addition to random intercept model giving a different intercept value for each observation, here we ad a random slope for each observation. This allows us to see the effect of time (weeks). The estimates for the explanatory variables are again the same compared with the two previous models. Standard error for explanatory variable #week# is higher and for explanatory variable #treatment# lower compared with the previous model. Here, the standard deviation for the random factor #subject# is higher than in the Random intercept model without the slope, so adding the random factor “week” has increased the standard deviation of the “subject”. This means that “subject” explains more of the variation now.
According to the ANOVA test, the fit against the comparison model is quite good as p<0.05 (0.026).
#Create a random intercept and random slope model.
BPRS_ref2 <- lmer(bprs ~ week * treatment + (week | subject), data = BPRSL, REML = FALSE)
summary(BPRS_ref2)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week * treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2744.3 2775.4 -1364.1 2728.3 352
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0512 -0.6271 -0.0768 0.5288 3.9260
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.9964 8.0620
## week 0.9687 0.9842 -0.51
## Residual 96.4707 9.8220
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 47.8856 2.2521 21.262
## week -2.6283 0.3589 -7.323
## treatment2 -2.2911 1.9090 -1.200
## week:treatment2 0.7158 0.4010 1.785
##
## Correlation of Fixed Effects:
## (Intr) week trtmn2
## week -0.650
## treatment2 -0.424 0.469
## wek:trtmnt2 0.356 -0.559 -0.840
#Perform an ANOVA test on the two models.
anova(BPRS_ref1, BPRS_ref2)
## Data: BPRSL
## Models:
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## BPRS_ref2: bprs ~ week * treatment + (week | subject)
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_ref1 7 2745.4 2772.6 -1365.7 2731.4
## BPRS_ref2 8 2744.3 2775.4 -1364.1 2728.3 3.1712 1 0.07495 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Here, standard deviation of the random effects “subject” and “week” has increased slightly, meaning that they explain the variation slightly more than in the previous model. The estimates for the explanatory variables have changed only slightly compared with the previous models. Standard error for explanatory variable #week# is higher and for explanatory variable #treatment# lower compared with the previous model. The standard deviation for the random factors have again increased slightly. In this model we can also see the interaction of the variables “week” and “treatment”.
According to the ANOVA test, the fit against the comparison model is not that good as p>0.05 (0.075)
#Draw the plot of BPRSL.
ggplot(BPRSL, aes(x = week, y = bprs, col = subject)) +
geom_line(aes(linetype = treatment)) +
scale_x_continuous(name = "Week") +
scale_y_continuous(name = "BPRS") +
theme(legend.position = "top") +
ggtitle("Observed")
#Create a vector of the fitted values.
Fitted <- fitted(BPRS_ref2)
#Create a new column fitted to BPRSL.
BPRSL <- BPRSL %>% mutate(Fitted)
#Draw the plot of fitted values of BPRSL.
ggplot(BPRSL, aes(x = week, y = Fitted, col = subject)) +
geom_line(aes(linetype = treatment)) +
scale_x_continuous(name = "Week") +
scale_y_continuous(name = "BPRS") +
theme(legend.position = "bottom") +
ggtitle("Fitted")
Graphics show what was discovered earlier: the fit of the model is not great.